package svc

import (
	"context"
	"fmt"
	"net/http"
	"oil-station-backend/internal/config"
	"oil-station-backend/internal/middleware"
	"oil-station-backend/internal/model"

	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/rest"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type ServiceContext struct {
	Config        config.Config
	DB            *gorm.DB
	UserModel     *model.UserModel
	FuelTypeModel *model.FuelTypeModel
	OrderModel    *model.OrderModel
	InventoryModel *model.InventoryModel
	JWTAuth       rest.Middleware
	AdminAuth     rest.Middleware
}

func NewServiceContext(c config.Config) *ServiceContext {
	db, err := gorm.Open(mysql.Open(c.MySQL.DataSource), &gorm.Config{})
	if err != nil {
		panic(err)
	}

	// 跳过自动迁移，使用SQL脚本初始化数据库

	return &ServiceContext{
		Config:        c,
		DB:            db,
		UserModel:     model.NewUserModel(db),
		FuelTypeModel: model.NewFuelTypeModel(db),
		OrderModel:    model.NewOrderModel(db),
		InventoryModel: model.NewInventoryModel(db),
		JWTAuth:       JWTAuth(c.Auth.AccessSecret),
		AdminAuth:     middleware.NewAdminAuthMiddleware(c.Auth.AccessSecret).Handle,
	}
}

// JWT中间件
func JWTAuth(secret string) rest.Middleware {
	return func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			// 添加CORS头，允许跨域请求
			w.Header().Set("Access-Control-Allow-Origin", "*")
			w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
			w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
			
			// 处理OPTIONS预检请求
			if r.Method == "OPTIONS" {
				w.WriteHeader(http.StatusOK)
				return
			}
			
			// 从请求头获取JWT令牌
			authHeader := r.Header.Get("Authorization")
			if authHeader == "" || len(authHeader) < 7 || authHeader[:7] != "Bearer " {
				fmt.Printf("JWT认证失败: 缺少有效的认证令牌, Header: %s\n", authHeader)
				http.Error(w, "未授权：缺少有效的认证令牌", http.StatusUnauthorized)
				return
			}

			tokenString := authHeader[7:]
			token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
				if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
					return nil, fmt.Errorf("无效的令牌签名方法")
				}
				return []byte(secret), nil
			})

			if err != nil {
				fmt.Printf("JWT认证失败: 令牌解析错误: %v\n", err)
				http.Error(w, fmt.Sprintf("未授权: %v", err), http.StatusUnauthorized)
				return
			}

			if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
				// 将用户信息添加到请求上下文
				fmt.Printf("JWT认证成功: 用户ID: %v, 用户名: %v, 角色: %v\n", 
					claims["id"], claims["username"], claims["role"])
				r = r.WithContext(context.WithValue(r.Context(), "claims", claims))
				next(w, r)
			} else {
				fmt.Printf("JWT认证失败: 无效的令牌\n")
				http.Error(w, "未授权", http.StatusUnauthorized)
			}
		}
	}
}